//
//  YZMAuthCodeView.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/3/30.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMAuthCodeView.h"
#import "YZMHintInputView.h"
#import "YZClient+Account.h"
#import "YZGeneralResultModel.h"
#import "YZMAlertView.h"
#import "YZClient.h"
#import "CheckCodeView.h"
@interface YZMAuthCodeView ()<CheckCodeViewDelegate>
@property (nonatomic, strong) YZMHintInputView *authCodeView;
@property (nonatomic, strong) YZMHintInputView *phoneNumberView;
@property (nonatomic, strong) UIButton *sendMsgButton;
@property (nonatomic, copy) NSString *hintMessage;
@property (nonatomic, assign) NSInteger timeCount;
@property (nonatomic, assign) BOOL getAuthFlag;
@property (nonatomic, strong) CheckCodeView *codeView;

@end

@implementation YZMAuthCodeView

- (id)initWithScene:(SEND_CODE_SCENE)scene {
    if (self = [super init]) {
        self.scene = scene;
        self.getAuthFlag = NO;
        [self createObjects];
    }
    return self;
}

- (void)checkIfNeedStartTimerForInterval:(NSInteger)interval {
    if (interval > 0) {
        self.timeCount = interval;
        [self refreshButton];
    }
}

- (void)setPhoneStr:(NSString *)phoneStr {

    _phoneStr = phoneStr;
}

- (NSString *)hintMessage {
    
    if (self.scene == SEND_CODE_SCENE_FOR_REGISTER) {
        
        _hintMessage =  [NSString stringWithFormat:@"验证码已经发往%@，请稍等！", self.phoneStr];
    } else {
        
        _hintMessage =  [NSString stringWithFormat:@"验证码已经发往%@，请稍等！", self.phoneNumberView.textField.text];
    }
    
    return _hintMessage;
}

- (UITextField *)textField {
    return self.authCodeView.textField;
}

- (UITextField *)phoneTextField {
    return self.phoneNumberView.textField;
}

- (void)createObjects {
    
    WS(ws)
    if (self.scene == SEND_CODE_SCENE_FOR_REGISTER) {
        
        self.authCodeView = [[YZMHintInputView alloc] init];
        [self addSubview:self.authCodeView];
        self.authCodeView.lineTopView.hidden=NO;
        self.authCodeView.lineBottomView.hidden=NO;
        [self.authCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(ws).with.offset(14);
            make.left.right.equalTo(ws);
            make.height.mas_equalTo(InputViewHeight);
        }];
    } else {

        self.phoneNumberView = [[YZMHintInputView alloc] init];
        [self addSubview:self.phoneNumberView];
        [self.phoneNumberView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(ws).with.offset(14);
            make.left.right.equalTo(ws);
            make.height.mas_equalTo(InputViewHeight);
        }];
        self.phoneNumberView.inputLabel.text = @"手机号";
        if (self.scene == SEND_CODE_SCENE_FOR_BIND_NEWMOBILE) {
            self.phoneNumberView.inputLabel.text = @"新手机号";
        }
        self.phoneNumberView.lineTopView.hidden=NO;
        if (YZMUserServiceInstance.user.detail.loginMobileNoHidden) {
            self.phoneNumberView.textField.text = YZMUserServiceInstance.user.detail.loginMobileNoHidden;
        }
        
        if (self.scene == SEND_CODE_SCENE_FOR_BIND_NEWMOBILE) {
            
            self.phoneNumberView.textField.text = @"";
        }
        
        if (self.scene == SEND_CODE_SCENE_FOR_UNBIND_MOBILE) {
            
            self.phoneNumberView.textField.enabled = NO;
        }
        
        self.phoneNumberView.textField.placeholder = @"请输入手机号码";
        self.phoneNumberView.textField.keyboardType = UIKeyboardTypeNumberPad;
        self.authCodeView = [[YZMHintInputView alloc] init];
        [self addSubview:self.authCodeView];
        [self.authCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(ws.phoneNumberView.mas_bottom);
            make.left.right.equalTo(ws);
            make.height.mas_equalTo(InputViewHeight);
        }];
        
        self.phoneNumberView.lineBottomView.hidden = YES;
        [self.authCodeView updateLineIndentationMethod:self.authCodeView.lineTopView enumeration:LINE_INDENT_SCENE_LEFT indentValue:ControlSpacing15];
    }

    self.authCodeView.inputLabel.text = @"验证码";
    self.authCodeView.textField.placeholder = @"请输入验证码";
    self.authCodeView.textField.keyboardType = UIKeyboardTypeNumberPad;
    self.authCodeView.lineBottomView.hidden=NO;
    
    self.sendMsgButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.authCodeView addSubview:self.sendMsgButton];
    [self.sendMsgButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.sendMsgButton setTitleColor:[YZMAppStyle colorForIconColor] forState:UIControlStateNormal];
    [self.sendMsgButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self.sendMsgButton addTarget:self action:@selector(sendButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.authCodeView appendRightWidget:self.sendMsgButton isShowSegmentLine:YES];
}

- (void)sendButtonPressed:(UIButton *)send {
    if (self.voiceAuthEvent) {
        self.voiceAuthEvent();
    }
    
    if (self.scene == SEND_CODE_SCENE_FOR_FORGET_PWD) {
        if ([self.phoneNumberView.textField.text length] != 11) {
            [MBProgressHUD showMessage:@"输入正确的手机号码"];
            return;
        }
    }
    
    if (self.scene == SEND_CODE_SCENE_FOR_BIND_NEWMOBILE) {
        if (![self.phoneNumberView.textField.text yz_isValidPhoneString]) {
            
            [MBProgressHUD showMessage:@"输入正确的手机号码"];
            return;
        }
    }
    
    if (self.timeCount > 0) {
        
        [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@秒后可使用", @(self.timeCount)]];
        return;
    }
    
    WS(ws)
    
    switch (self.scene) {
        case SEND_CODE_SCENE_FOR_REGISTER: {
            [YZClient getMobileAuthCode:self.phoneStr success:^(NSURLSessionDataTask *task,id responseObject) {
                [ws returnWithResult:responseObject];
            } failure:^(NSError *error) {
                [error yz_showMessage];
            }];
            
            break;
        }
        case SEND_CODE_SCENE_FOR_FORGET_PWD: {
            [self showCodeView];
            
        }
            break;
        case SEND_CODE_SCENE_FOR_FORGET_WITHDRAW: {
            
            [YZClient forget_getAuthCodeWithVoice:FALSE success:^(NSURLSessionDataTask *task,id responseObject) {
                [ws returnWithResult:responseObject];
            } failure:^(NSError *error) {
                [error yz_showMessage];
            }];
            
        }
            break;
            
        case SEND_CODE_SCENE_FOR_UNBIND_MOBILE:{
            [self showCodeView];
        }
        
            break;
            
        case SEND_CODE_SCENE_FOR_BIND_NEWMOBILE:{
            
            if ([self.phoneNumberView.textField.text isEqualToString:YZMUserServiceInstance.user.detail.loginMobileNoHidden]) {
                
                YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"新手机号码不能和旧手机号码相同"];
                alertView.contentLabel.font = [YZMAppStyle mediumSizeFont];
                [alertView show];
                
                return;
            }
            [self showCodeView];
        }
            
            break;
            
        default:{
            break;
        }
    }
}

- (void)showCodeView{
    if (kNetworkNotReachability) {
        
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        
        return;
    }
  _codeView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CheckCodeView class]) owner:self options:nil][0];
    _codeView.delegate = self;
    [_codeView show];
}

- (void)checkCode:(NSString *)strCode{
    WS(ws);
    NSInteger i = self.scene;
    switch (i) {
        case SEND_CODE_SCENE_FOR_FORGET_PWD:{
            [YZClient forget_getMobileAuthCode:self.phoneNumberView.textField.text withCheckCode:strCode success:^(NSURLSessionDataTask *task, id responseObject) {
                [ws returnWithResult:responseObject];
            } failure:^(NSError *error) {
                [error yz_showMessage];
            }];
        }
            break;
        case SEND_CODE_SCENE_FOR_UNBIND_MOBILE:{
            [YZClient unbind_getMobileImessagewithCheckCode:strCode success:^(NSURLSessionDataTask *task, id responseObject) {
                [ws returnWithResult:responseObject];
            } failure:^(NSError *error) {
                [error yz_showMessage];
            }];
        }
            break;
        
        case SEND_CODE_SCENE_FOR_BIND_NEWMOBILE:{
            [YZClient bind_NewCheckMobileWithMobile:self.phoneNumberView.textField.text withCheckCode:strCode success:^(NSURLSessionDataTask *task, id responseObject) {
                [ws returnWithResult:responseObject];
            } failure:^(NSError *error) {
                [error yz_showMessage];
            }];
        }
            break;
    }
}

- (void)returnWithResult:(YZGeneralResultModel *)responseObject {
    
    if (responseObject.code == 501) {
        
        [self.sendMsgButton setTitle: @"获取验证码" forState: UIControlStateNormal];
//        [self.sendMsgButton setTitleColor:[YZMAppStyle colorForRiseText] forState:UIControlStateNormal];
        self.sendMsgButton.enabled = YES;
        if (self.scene == SEND_CODE_SCENE_FOR_BIND_NEWMOBILE) {
            [self removeCodeView];
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:responseObject.resultMessage];
            alertView.contentLabel.font = [YZMAppStyle mediumSizeFont];
            [alertView show];
        }else{
            
        [responseObject showMessage];
        }
        return;
    } else if (responseObject.code == 100) {
        [self removeCodeView];
        [MBProgressHUD showMessage:self.hintMessage];
        [self checkIfNeedStartTimerForInterval:60];
    } else if (responseObject.code == 101) {
        [self removeCodeView];
        if ([responseObject.data isKindOfClass:[NSDictionary class]]) {
            [self checkIfNeedStartTimerForInterval:[responseObject.data[@"interval"] integerValue]];
        }
    } else {
        
        [responseObject showMessage];
    }
}

- (void)removeCodeView{
    if (self.codeView != nil) {
        [self.codeView removeFromSuperview];
    }
}


- (void)refreshButton {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startRefresh) userInfo:nil repeats:YES];
    [self.timer fire];
}

- (void)startRefresh {
    
    if (self.timeCount < 1) {
        [self stopTimer];
        [self.sendMsgButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.sendMsgButton setTitleColor:[YZMAppStyle colorForIconColor] forState:UIControlStateNormal];
        self.sendMsgButton.enabled = YES;
    } else {
        NSString *titleStr = [NSString stringWithFormat:@"%@秒后重发", @(self.timeCount)];
        [self.sendMsgButton setTitleColor:[YZMAppStyle colorForIconColor] forState:UIControlStateNormal];
        [self.sendMsgButton setTitle:titleStr forState:UIControlStateNormal];
        self.sendMsgButton.enabled = NO;
        self.getAuthFlag = YES;
    }
    
    self.timeCount --;
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
}

@end
